import os
import base64
import requests


def get_baidu_dish_access_token(api_key, secret_key):
    """
    使用 AK, SK 生成鉴权签名(Access Token)
    :return: access_token,或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": str(api_key).strip(), "client_secret": str(secret_key).strip()}
    return str(requests.post(url, params=params).json().get("access_token"))


def get_baidu_dish_result(token, path):
    print(path)
    print(os.path.exists(path))
    url = f"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token={token}"
    with open(path, "rb") as f:
        image = base64.b64encode(f.read())
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        # 'Accept': 'application/json'
    }
    payload = {
        "image": image,
        # "top_num": 5,
        # "filter_threshold": 0.95,
    }
    response = requests.post(url, data=payload, headers=headers)
    print(response.text)
    if response.status_code != 200:
        raise Exception("识别请求失败")
    result = response.json()
    return [i.get("name") for i in result.get("result",[]) if i]
